<?php

namespace app\common\model\xiluhouse;

use think\Model;

class VillageBroker extends Base
{

    // 表名
    protected $name = 'xiluhouse_village_broker';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public function village(){
        return $this->belongsTo('Village','village_id','id',[],'inner')->setEagerlyType(0);
    }


    /**
     * 关联经纪人
     * @param $village
     * @param $broker_user_ids
     * @param string $type
     * @return array|bool|false|\think\Collection|\think\model\Collection
     * @throws \think\Exception
     */
    public static function setBrokerIds($village,$broker_user_ids,$type='add'){
        if($type == 'add'){
            $broker_user_ids = is_array($broker_user_ids) ? $broker_user_ids : explode(',', $broker_user_ids);
            foreach ($broker_user_ids as &$broker_user_id) {
                $broker_user_id = ['village_id'=>$village->id, 'broker_user_id'=>$broker_user_id];
            }
            return (new self())->saveAll($broker_user_ids);
        }else{
            if($broker_user_ids) {
                $insertBrokerIds = [];
                $broker_user_ids = is_array($broker_user_ids) ? $broker_user_ids : explode(',', $broker_user_ids);
                self::whereNotIn('broker_user_id', $broker_user_ids)->where('village_id', $village->id)->delete();
                foreach ($broker_user_ids as &$broker_user_id) {
                    if(self::where('village_id',$village->id)->where('broker_user_id',$broker_user_id)->count()<1)
                        $insertBrokerIds[] = ['village_id'=>$village->id, 'broker_user_id'=>$broker_user_id];
                }
                if($insertBrokerIds) {
                    return (new self())->saveAll($insertBrokerIds);
                }
            }else {
                self::where('village_id', $village->id)->delete();
            }
        }
    }

}
